/**
 *    @file       epoll.cpp
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       02/12/2014 06:30:51 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com 
 */
#include "epoll.h"

epoll::epoll()
	: m_fd(0), m_size(0), m_wait_time(0), m_events(NULL), m_avail_num(0), m_avail_index(0)
{

}

epoll::~epoll()
{
	if (m_events)
	{
		delete [] m_events;
	}
	close(m_fd);
}

bf_int_t epoll::init(bf_int_t epoll_size, bf_int_t wait_time)
{
	m_size = epoll_size;
	m_wait_time = wait_time;
	m_fd = epoll_create(m_size);
	if (m_fd < 0)
	{
		return BF_ERROR;
	}
	m_events = new bf_epoll_event_t[m_size];
	return BF_OK;
}

bf_int_t epoll::add(bf_int_t sockfd, bf_int_t events, void *append_data)
{
	bf_int_t op = EPOLL_CTL_ADD;
	bf_epoll_event_t event_tmp;
	event_tmp.events = events;
	event_tmp.data.ptr = append_data;
	bf_int_t ret = epoll_ctl(m_fd, op, sockfd, &event_tmp);
	return (ret == 0)? BF_OK:BF_ERROR;
}

bf_int_t epoll::del(bf_int_t sockfd, void *append_data)
{
	bf_int_t op = EPOLL_CTL_DEL;
	bf_epoll_event_t event_tmp;
	event_tmp.events = 0;
	event_tmp.data.ptr = append_data;
	bf_int_t ret = epoll_ctl(m_fd, op, sockfd, &event_tmp);
	return (ret == 0)? BF_OK:BF_ERROR;
}
bf_int_t epoll::modify(bf_int_t sockfd, bf_int_t events, void *append_data)
{
	bf_int_t op = EPOLL_CTL_MOD;
	bf_epoll_event_t event_tmp;
	event_tmp.events = events;
	event_tmp.data.ptr = append_data;
	bf_int_t ret = epoll_ctl(m_fd, op, sockfd, &event_tmp);
	return (ret == 0)? BF_OK:BF_ERROR;
}

bf_int_t epoll::wait()
{
	return wait(m_wait_time);
}

bf_int_t epoll::wait(bf_int_t wait_time)
{
	m_avail_num = 0;
	m_avail_index = 0;
	bf_int_t cnt = epoll_wait(m_fd, m_events, m_size, wait_time);
	if (cnt < 0)
	{
		return BF_ERROR;
	}
	else if (cnt == 0)
	{
		return BF_FALSE;
	}
	m_avail_num = cnt;
	return BF_TRUE;
}


